package com.iloomo.filter;

import com.alibaba.fastjson.JSONObject;
import com.iloomo.util.PageData;
import com.iloomo.util.RedisUtil;
import com.iloomo.util.Tools;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @version 1.0
 * @className PreFilter
 * @date 2019/4/26 19:40
 * @description Zuul的服务过滤
 */
@Component
public class PreFilter extends ZuulFilter {
    private static String KEY = "KLF7KGtS9eZx7DWQ";

    private static String IV = "SRl2wsWc9OV3zzch";

    @Override
    public String filterType() {//拦截类型设置
        return "pre"; //标准拦截
    }

    @Override
    public int filterOrder() {//拦截优先级设置
        return 0;
    }

    @Override
    public boolean shouldFilter() {//是否开启过滤或拦截,改为true
        return true;
    }

    @org.springframework.beans.factory.annotation.Value("${iloomo.debug}")
    private String iloomoDebug;

    @Override
    public Object run() {
        com.alibaba.fastjson.JSONObject json = new JSONObject();
        json.put("success", false);
        boolean decode = false;
        RequestContext ctx = RequestContext.getCurrentContext();//得到request上下文对象，里面包含了此次访问的所有环境、参数支持，相当于一个工厂
        ctx.getResponse().setCharacterEncoding("UTF-8");
        HttpServletRequest request = ctx.getRequest();
        HttpServletResponse response = ctx.getResponse();
        String path = request.getServletPath();
        if (!path.matches(Config.PUBLIC)) {
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers", "authorization, content-type");
            response.setHeader("Access-Control-Allow-Methods", "POST,GET");
            response.setHeader("Access-Control-Expose-Headers", "X-forwared-port, X-forwarded-host");
            response.setHeader("Vary", "Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
        }
        Map<String, List<String>> requestQueryParams = null;
        PageData pageData = new PageData(request);
        requestQueryParams = ctx.getRequestQueryParams();

        if (requestQueryParams == null) {
            requestQueryParams = new HashMap<String, List<String>>();
        }
        if ("false".equals(iloomoDebug)) {
            if (path.matches(Config.NO_ALL_INTERCEPTOR_PATH)) {
                //不需要token和appid
            } else {
                String loomoAppId = pageData.getString("loomoApp_id");
                String token = pageData.getString("token");
                if (path.matches(Config.NO_APP_ID_INTERCEPTOR_PATH)) {
                    //不需要app_id的
                } else {
                    if (Tools.notEmpty(loomoAppId)) {//企业后台登录的
                        String businessId = RedisUtil.get(loomoAppId);
                        if (businessId == null) {
                            json.put("msg", "非法loomoApp_id");
                            ctx.setResponseBody(json.toString());
                            ctx.setSendZuulResponse(false);
                        } else {
                            List<String> appIdArrayList = new ArrayList<String>();
                            appIdArrayList.add(loomoAppId);
                            requestQueryParams.put("loomoApp_id", appIdArrayList);
                            List<String> arrayList = new ArrayList<String>();
                            arrayList.add(businessId);
                            requestQueryParams.put("business_id", arrayList);
                            decode = true;
                        }
                    } else if (Tools.notEmpty(token)) {
                        String userId = RedisUtil.get(token);
                        if (userId == null) {
                            json.put("msg", "非法token");
                            ctx.setResponseBody(json.toString());
                            ctx.setSendZuulResponse(false);
                        }
                    } else {
                        json.put("msg", "非法非法");
                        ctx.setResponseBody(json.toString());
                        ctx.setSendZuulResponse(false);
                    }
                }
                if (path.matches(Config.NO_TOKEN_INTERCEPTOR_PATH)) {
                    //不需要token的。
                } else {
                    String userIdToken = pageData.getString("token");
                    if (Tools.notEmpty(userIdToken)) {    //验证token
                        String userId = RedisUtil.get(userIdToken);
                        if (userId == null) {
                            json.put("msg", "非法token");
                            ctx.setResponseBody(json.toString());
                            ctx.setSendZuulResponse(false);
                        } else {
                            decode = true;
                        }
                    } else {
                        json.put("msg", "");
                        ctx.setResponseBody(json.toString());
                        ctx.setSendZuulResponse(false);
                    }
                }

                ctx.setRequestQueryParams(requestQueryParams);
            }
        }
        ctx.setRequestQueryParams(requestQueryParams);
        return null;
    }


}